package com.ht.medicaltreatment.activity

import android.content.Intent
import android.view.View
import cn.bingoogolapple.qrcode.core.BarcodeType
import cn.bingoogolapple.qrcode.core.QRCodeView
import com.gym.baselib.base.BaseActivity
import com.ht.medicaltreatment.R
import kotlinx.android.synthetic.main.activity_zbar_layout.*
import kotlinx.android.synthetic.main.include_title_layout.*
import kotlinx.android.synthetic.main.view_stub_layout.*

//二维码扫描
class ScanZBarActivity:BaseActivity() {

    override fun getLayoutId() = R.layout.view_stub_layout

    override fun init() {
        viewStub.setOnInflateListener { viewStub, view ->
            tvViewStubProgress.visibility = View.GONE
            imgViewStubProgress.visibility = View.GONE

            setTitle("扫一扫")
            imgBack.setOnClickListener { finish() }

            zbarview.setType(BarcodeType.ALL,null)
            zbarview.startCamera()
            zbarview.startSpot()
            zbarview.setDelegate(object : QRCodeView.Delegate{
                override fun onScanQRCodeSuccess(result: String?) {
                    if(result?.isEmpty() == true)return
                    zbarview.stopSpot()
                    zbarview.stopCamera()
                    zbarview.closeFlashlight()
                    val intent = Intent()
                    intent.putExtra("resultUid",result)
                    setResult(RESULT_OK,intent)
                    finish()
                }

                override fun onCameraAmbientBrightnessChanged(isDark: Boolean) {
                    //isDark 是否变暗
                    if(isDark){
                        zbarview.openFlashlight()
                    }
                }

                override fun onScanQRCodeOpenCameraError() {
                    //打开相机错误
                }
            })
        }

        viewStub.postDelayed({
            viewStub.layoutResource = R.layout.activity_zbar_layout
            viewStub.inflate()
        },300)
    }

    override fun onDestroy() {
        super.onDestroy()
        zbarview.stopSpot()
        zbarview.stopCamera()
        zbarview.closeFlashlight()
    }

}
